const WebSocket = require('ws');
const http = require('http');
const fs = require('fs');
const { type } = require('os');

let clients = new Set();

// 心跳配置
const HEARTBEAT_INTERVAL = 30000; // 30秒
const HEARTBEAT_TIMEOUT = 10000; // 10秒无响应判定死亡

const server = http.createServer((req, res) => {
    if (req.method === 'POST' && req.url === '/notify') {
        let body = '';
        req.on('data', chunk => body += chunk);
        console.log('body', body)
        req.on('end', () => {
            try {
                const { version } = JSON.parse(body);
                console.log('version', version)
                if (version) {
                    versionNotifier(version);
                    res.writeHead(200);
                    res.end('OK');
                } else {
                    res.writeHead(400);
                    res.end('Missing version');
                }
            } catch {
                res.writeHead(400);
                res.end('Invalid JSON');
            }
        })
    }
})
// 创建WebSocket服务器
const wss = new WebSocket.Server({ server });

let currentVersion = '1.0.0'
// 每个连接
wss.on('connection', (ws, req) => {
    console.log('🟢 新客户端连接');

    clients.add(ws);

    // 监听消息
    ws.on('message', (msg) => {
        if (Buffer.isBuffer(msg)) msg = msg.toString('utf-8')
        try {
            // 收到客户端ping
            if (msg === 'ping') {
                // 响应客户端 pong
                ws.send('pong');
                return 
            }
            const data = msg === 'ping' ? data : JSON.parse(msg);
            console.log('📨 收到消息：', data);
        } catch (error) {
            console.log(error)
        }
    })

    // 关闭连接
    ws.on('close', () => {
        clients.delete(ws);
        console.log('❌ 用户断开连接');
    })

    ws.on('error', () => {
        clients.delete(ws);
        console.log('⚠️ 连接错误');
  });
})

function versionNotifier(vaersion) {
    for (const ws of clients) {
        if (ws.readyState === WebSocket.OPEN) {
             ws.send(JSON.stringify({
                type: 'version',
                message: vaersion,
            }));
        }
    }
}


server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});